/**
 * Created by jinkerjiang on 15/11/26.
 * 资源加载
 */
define(function (require) {
    /**
     * 资源加载
     * @param {Array.<string>} urls
     * @param {function(Array.<{url:string,loaded:boolean,complete:boolean}>)} callback 加载完成回调
     * @constructor
     */
    var ResourceLoader = function (urls, callback) {
        var configs = [];
        for (var i = 0; url = urls[i]; i++) {
            configs.push({url: url, loaded: false, complete: false});
        }

        function onFinish(i, loaded) {
            return function () {
                var configItem = configs[i];
                configItem.loaded = loaded;
                configItem.complete = true;

                if (typeof callback === 'function') {
                    var flag = true;

                    var config;
                    for (var j = 0; config = configs[j]; j++) {
                        if (!config.complete) {
                            flag = false;
                            break;
                        }
                    }

                    if (flag) {
                        callback(configs);
                    }
                }
            }
        }

        var url;
        for (var i = 0; url = urls[i]; i++) {
            var img = new Image();

            img.onload = onFinish(i, true);
            img.onerror = onFinish(i, false);

            img.src = url;
        }
    };

    return {
        /**
         * @param {Array.<string>} assets
         * @param {function(Array.<{url:string,loaded:boolean,complete:boolean}>)} callback 加载完成回调
         */
        load: function (assets, callback) {
            return new ResourceLoader(assets, callback);
        }
    };
});